module IPFS.Client.Command.Bitswap (
  stat,
  wantlist,
  Wantlist(..)
) where
import Prelude

import Data.Argonaut (Json)
import Data.Argonaut.Decode (class DecodeJson, decodeJson, (.:))

import Data.Either (Either)
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)

import Data.Maybe (Maybe(..))
import Data.Tuple.Nested ((/\))
import Effect.Aff (Aff)
import Foreign.Object as O
import IPFS.Client as C
import IPFS.Client.Command (Command, defCommand, genQSObject)
import IPFS.Client.Command.Common (CIDObject,Stat)
import IPFS.Client.Utils.SendRequest (execJsonCommand)

------------------------stat---------------------------------
statCommand::Command
statCommand = defCommand { path = "bitswap/stat", args = Nothing ,qs = O.empty}

stat::C.Client -> Aff (Either String Stat)
stat client = execJsonCommand client statCommand

------------------------wantlist---------------------------------
data Wantlist = Wantlist {
  keys::(Array CIDObject)
} 

derive instance genericWantlist :: Generic Wantlist _
instance showWantlist :: Show Wantlist where
  show s = genericShow s

instance wantlistDecodeJson :: DecodeJson Wantlist where
   decodeJson json = do
    dJson::O.Object Json    <- decodeJson json
    keys::Array CIDObject　<- dJson .: "Keys"
    pure $ Wantlist {keys:keys}

wantlistCommand::Maybe String -> Command
wantlistCommand mayPeerId = defCommand {path = "bitswap/wantlist",args = Nothing,qs = genQSObject ["peer" /\ mayPeerId] O.empty }

wantlist::C.Client -> Maybe String -> Aff (Either String Wantlist)
wantlist client peer = execJsonCommand client $ wantlistCommand peer